<!--
@description    绩效详情
@author         秦俊强
@email          458112865@qq.com
@create         2020-04-16 19:20
-->

<template>
  <div class="ant-card ant-card-body">

    <!-- 公共菜单区 start -->
    <div class="menu-box">
      <a-row :gutter="10">
        <a-col :md="24" :sm="24">
          <div class="query-date">
            <span>考核期：</span>
            <a-select v-if="!yearMonthList.loading"
                      :value="yearMonthList.val.text" @change="changeDate" style="width: 150px">
              <a-select-option v-for="date in yearMonthList.arr"
                               :key="date.value">{{ date.text }}</a-select-option>
            </a-select>
            <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>
          </div>

          <div class="query-depart">
            <span>组织类型：</span>
            <a-select v-if="!departInfo.loading"
                      :value="departInfo.arr[departInfo.index].name"
                      @change="departChange">
              <a-select-option v-for="depart in departInfo.arr"
                               :key="depart.code">{{ depart.name }}</a-select-option>
            </a-select>
            <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>
          </div>

          <div class="query-target">
            <span>考核指标：</span>
            <a-select mode="multiple" placeholder="全部指标"
                      :allowClear="true" :maxTagCount="0"
                      :dropdownMatchSelectWidth="false"
                      :showArrow="true"
                      :value="targetInfo.indexs"
                      @change="targetChange">
              <a-select-option v-for="target in targetInfo.arr"
                               :key="target.code"
                               :title="target.name">{{ target.name }}</a-select-option>
            </a-select>
          </div>

          <div class="query-target">
            <span>维度：</span>
            <a-select mode="multiple" placeholder="全部维度"
                      :allowClear="true" :maxTagCount="0"
                      :dropdownMatchSelectWidth="false"
                      :showArrow="true"
                      :value="dimensionInfo.indexs"
                      @change="dimensionChange">
              <a-select-option v-for="dim in dimensionInfo.arr"
                               :key="dim.code"
                               :title="dim.name">{{ dim.name }}</a-select-option>
            </a-select>
          </div>
          <div class="query-target">
             <span><a-checkbox @change="onChangeIsTotal" :checked="isTotal">只看简报</a-checkbox></span>
          </div>
        </a-col>
      </a-row>
    </div>
    <!-- 公共菜单区 end -->


    <!-- 表格数据 start -->
    <div class="table-box">
      <div class="table-box" v-if="tableKey">
        <a-table :loading="loading" :pagination="false"
                 :scroll="tableData[tableKey].scroll"
                 :columns="tableData[tableKey].columns"
                 :dataSource="tableData[tableKey].dataSource"
                 :rowClassName="isLine"
        ></a-table>

        <!-- 分页 start -->
        <div class="pagination-box">
          <a-pagination :current="pageData.pageNo"
                        :pageSize="pageData.pageSize"
                        :total="pageData.total"
                        :pageSizeOptions="['10', '15', '20', '30']"
                        showSizeChanger
                        @change="changePage"
                        @showSizeChange="onShowSizeChange" />
        </div>
        <!-- 分页 end -->

      </div>
    </div>
    <!-- 表格数据 end -->

  </div>
</template>



<script>
  /* api 通用服务 */
  import { apiService } from '@/api/api.service.js';

  /**
   * api 接口
   *
   * getKpiYearMonthList => 获取评分年月信息
   * getKaFillConditions => 绩效管理员绩效审核详情/审核员绩效考核详情-列表条件
   * getIndexCodes => 获取指标下拉菜单
   * indexAttrs => 获取维度下拉菜单
   * getAuditDetailDatagrid => 获取列表信息
   * */
  import {
    getKpiYearMonthList, getKaFillConditions, getIndexCodes, indexAttrs, getAuditDetailDatagrid
  } from '@/api/api.js';

  /* 引入表格配置文件 */
  import { getCommonTabTem } from '../kpi/components/tableCommon/table.config.js';





  export default {
    data() {
      return {
        loading: true,

        /* 年月下拉菜单 */
        yearMonthList: {
          loading: true,
          arr: [],    // 可选择的年月列表
          val: {}     // 已选年月，默认数组第 0 个
        },

        /* 部门下拉选项菜单 */
        departInfo: { loading: true, arr: [], index: 0 },

        /* 指标下拉选项菜单 */
        targetInfo: { arr: [], indexs: [] },

        /* 维度 */
        dimensionInfo: { arr: [], indexs: [] },

        /* 表格参数 */
        tableData: {},

        /* 标记当前选择的部门 */
        tableKey: '',

        /* 分页参数 */
        pageData: {
          pageNo: 1,
          pageSize: 10,
          total: null
        },

        /* 用于延时调用搜索接口 */
        timeout: null,
        /* 是否只看简报 */
        isTotal: true
      };
    },

    created() {
      /* 获取评分年月 */
      this.yearMonthList.loading = true;
      apiService(getKpiYearMonthList()).then((res) => {
        let list = res.result || [];
        this.yearMonthList = {
          loading: false,
          arr: list || [],
          val: list[0] || {}
        };

        this.getConditions();     // 获取部门下拉选项菜单
      }).catch((error) => {
        this.yearMonthList.loading = false;
        this.$message.error(error.message);
      });
    },

    methods: {
      /* 如果是分数行就高亮 */
      isLine(row) {
        if(row.showLine){
          if (row.indexValueName === '得分') { return 'row-line-more'; }
        }else {
          if(row.indexName === '总计' || row.indexName.indexOf("小计")!=-1){
            return 'row-line-more';
          }
        }
        return '';
      },


      /* 监听 考核期变化 */
      changeDate(code) {
        let arr = this.yearMonthList.arr;
        this.yearMonthList.val = arr.find((item) => { return (item.value === code); });
        this.pageData.pageNo = 1;
        this.getConditions();
        this.update();
      },

      /* 监听 组织切换 */
      departChange(code) {
        let arr = this.departInfo.arr;
        this.departInfo.index = arr.findIndex((item) => { return item.code === code });
        this.tableKey = arr[this.departInfo.index].code;
        this.pageData.pageNo = 1;

        this.getIndexCodes();
        this.update();
      },

      /**
       * 监听 考核指标变化
       *
       * 【逻辑】首先清除定时器，再开启定时器延时调用接口
       * 【原因】因为选择考核指标是多选，不能频繁调用接口，减少请求次数
       * */
      targetChange(codes) {
        clearTimeout(this.timeout);       // 清除定时器

        this.targetInfo.indexs = codes;
        let num = (codes.length === 0) ? 300 : 1300;  // 如果是清空操作，延时短一点；如果是多选，时间长一点；

        this.timeout = setTimeout(() => {
          this.pageData.pageNo = 1;
          this.update();
        }, num);
      },

      /**
       * 监听维度变化
       *
       * 【逻辑】首先清除定时器，再开启定时器延时调用接口
       * 【原因】因为选择考核指标是多选，不能频繁调用接口，减少重复请求
       * */
      dimensionChange(codes) {
        // 清除定时器
        clearTimeout(this.timeout);

        this.dimensionInfo.indexs = codes;
        let num = (codes.length === 0) ? 300 : 1300;  // 如果是清空操作，延时短一点；如果是多选，时间长一点；
        this.timeout = setTimeout(() => { this.update(); }, num);
      },

      /* 监听 页码改变 */
      changePage(pageNo) {
        this.pageData.pageNo = pageNo;
        this.update();
      },

      /* 监听 分页条数的改变 */
      onShowSizeChange(current, pageSize) {
        this.pageData.pageSize = pageSize;
        this.pageData.pageNo = 1;
        this.update();
      },
      /* 监听是否只看简报项的变化 */
      onChangeIsTotal(e) {
         this.isTotal = e.target.checked;
         this.pageData.pageNo = 1;
         this.update();
      },

      /* 获取表格数据 */
      update() {
        let pageData = this.pageData;
        let yearMonth = this.yearMonthList.val.value;
        let targetIndexs = this.targetInfo.indexs;
        let targets = (targetIndexs.length === 0) ? null : targetIndexs;
        let dimensions = (this.dimensionInfo.indexs.length === 0) ? null : this.dimensionInfo.indexs;

        let param = {
          indexGroup: this.tableKey,          // 组织类型
          indexYearMonth: yearMonth,          // 时间 YYYYMM
          indexCodes: targets,                // 考核指标
          indexAttrs: dimensions,             // 维度
          pageNo: pageData.pageNo,            // 跳转页数 默认 1
          pageSize: pageData.pageSize,         // 分页数 默认 10
          isTotal: this.isTotal,
        }

        this.loading = true;
        apiService(getAuditDetailDatagrid(param)).then((res) => {
          this.loading = false;

          let result = res.result || {};
          let records = result.records;
          debugger;
          this.tableData[this.tableKey].dataSource = records;
          this.pageData.total = result.total;
        }).catch((error) => {
          this.loading = false;
          this.pageData.total = null;
          this.$message.error(error.message);
        });
      },

      /* 初始化表头数据 */
      initTableData() {
        for (let i = 0; i < this.departInfo.arr.length; i++) {
          let item = this.departInfo.arr[i];
          let code = item.code;
          this.tableData[code] = this.getTabHeaderTem(item.tabHeader, code);
        }

        console.log(this.tableData);
        this.tableKey = this.departInfo.arr[this.departInfo.index].code;
        this.update();
      },

      /**
       * 返回表头模板，转换成第三方 UI 框架表格组件需要的格式
       * */
      getTabHeaderTem(arr, k) {
        let newArr = getCommonTabTem(arr, k);

        /* 接口返回数组的前 4 项都可以忽略，所以从第 5 个开始循环 */
        for (let i = 4; i < arr.length; i++) {
          let item = arr[i];

          newArr.splice(newArr.length - 1, 0, {
            title: item.name,
            align: 'center',
            width: 100,
            dataIndex: item.code,
            scopedSlots: { customRender: item.code },
          });
        }

        // 删除最后一个操作项，因为不需要编辑
        newArr.pop();

        /* 计算表格的横向滚动数值 */
        let num = (() => {
          return newArr.reduce((total, obj) => {
            let n = (typeof obj.width === 'number') ? obj.width : 0;
            return total + n;
          }, 0);
        })();

        return {
          scroll: { x: num, y: '500px' },
          columns: newArr,
          dataSource: [],
        };
      },

      /* 获取部门下拉选项菜单 */
      getConditions() {
        this.departInfo.loading = true;
        let param = {
            indexYearMonth : this.yearMonthList.val.value
        }
        apiService(getKaFillConditions(param)).then((res) => {
          this.departInfo.loading = false;
          this.departInfo.arr = res.result;   // 下拉菜单赋值

          this.getIndexCodes();               // 取指标下拉菜单，因为存在级联的依赖关系
          this.getIndexAttrsInfo();           // 获取维度下拉菜单
          this.initTableData();
        }).catch((error) => {
          this.departInfo.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 获取维度下拉选项菜单 */
      getIndexAttrsInfo() {
        this.dimensionInfo = { arr: [], indexs: [] };
        apiService(indexAttrs()).then((res) => {
          this.dimensionInfo.arr = res.result || [];
        }).catch((error) => {
          this.$message.error(error.message);
        });
      },

      /* 获取指标下拉选项菜单 */
      getIndexCodes() {
        let departInfo = this.departInfo;
        let param = { indexGroup: departInfo.arr[departInfo.index].code }

        this.targetInfo = { arr: [], indexs: [] };
        apiService(getIndexCodes(param)).then((res) => {
          this.targetInfo.arr = res.result || [];
        }).catch((error) => {
          this.$message.error(error.message);
        });
      }

    },
  };
</script>



<style lang="less" scoped>
  .menu-box {
    margin-bottom: 10px;

    [class*="query-"] {
      float: left;
      margin-right: 10px;
    }

    .query-depart {
      /deep/.ant-select {
        width: 120px;
      }
    }

    .query-date {
      /deep/.ant-calendar-picker-input {
        width: 100px;
      }
    }

    .query-target {
      /deep/.ant-select {
        width: 120px;
      }
    }

    .btn-box {
      float: right;
      button { margin-left: 4px; }
    }
  }

  .table-box {
    /*/deep/.ant-table th {
      white-space: nowrap;
      min-width: 90px;
    }*/

    /deep/.row-line-more {
      background-color: #fff0d8;
      font-weight: bold;

      &:hover td {
        background-color: #fff0d8;
      }
    }


    /deep/.ant-table td {
      height: 44px;
      padding: 5px 10px;

      input {
        height: 28px;
        padding: 4px 5px;
      }

      .weight-per, .weight-sec {
        input { width: 40% }
      }
    }

    .pagination-box {
      margin-top: 20px;
      float: right;
    }

    .btn-edit,
    .btn-save,
    .btn-cancel {
      color: @primary-color;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }
    .btn-cancel {
      margin-left: 10px;
    }
    .btn-disabled {
      color: #cccccc;
    }
  }
</style>


